package com.mh.study.springcloud.service;

import com.mh.study.springcloud.dao.UserReopsitory;
import com.mh.study.springcloud.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Optional;

/**
 * @author meng.han
 * @since 2022-04-17
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserReopsitory userReopsitory;

    @Autowired
    public UserDetailsServiceImpl(UserReopsitory userReopsitory) {
        this.userReopsitory = userReopsitory;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<MyUser> userOpt = userReopsitory.findOne(Example.of(new MyUser().setUsername(username)));
        if (userOpt.isEmpty()) {
            throw new UsernameNotFoundException("Not Found User! username=" + username);
        }
        MyUser user = userOpt.get();
        return new User(user.getUsername(), user.getPassword(), Collections.emptyList());
    }
}
